//
//  BDGanziSearchViewController.m
//  BeidouMall
//
//  Created by qie on 16/7/5.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDGanziSearchViewController.h"
#import "BDGoodDetailViewController.h"
#import "BDGanziTypeHeaderView.h"

#define kPageSize 5

@interface BDGanziSearchViewController () < UITableViewDelegate,
                                            UITextFieldDelegate,
                                            BDGanziTypeHeaderViewDelegate,
                                            UIScrollViewDelegate,
                                            SimplePopupViewDelegate >
{
    BDGanziTypeHeaderView *_typeHeaderView;
    NSMutableArray *_searchList;
    NSInteger _curPage;
    BOOL presentLoginView;
    NSString *_sortBy;
    NSString *_sortType;
    
    NSDictionary *levelDic;
    NSString *_lastSearchContent;
    NSDictionary *_tanslateDic;// 通过中文名称换为英文名称,因为国际化不支持中文作为key
    
    CGFloat beginOffsetY;
    BOOL willBeginScroll;
    BOOL showTop;
    UIImageView *navBarHairlineImageView;
    
    UIButton *_topButton;
    SimplePopupView *_popView;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *firstButton;
@property (weak, nonatomic) IBOutlet UIView *topContainerview;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topContainerviewConstraint;
@property (weak, nonatomic) IBOutlet UILabel *topNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *topPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *topScoreLabel;

@end

@implementation BDGanziSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadData:)];
    _searchList = [[NSMutableArray alloc] init];
    
    levelDic = @{@"便民":@"conveniency",@"民族特色":@"specialty",@"文化":@"culture",@"季产":@"season",
                 @"奢侈礼品":@"luxury",@"其他":@"other",@"民贸超市":@"privatelyCompany",@"糕点":@"pastry",
                 @"凉卤":@"cold_dish",@"食品":@"food",@"药材":@"medicinal",@"服饰":@"costume",
                 @"手工艺":@"handicraft",@"图书":@"book",@"生鲜":@"fresh",@"干货":@"dry_good",
                 @"非物质文化遗产":@"intangible_cultural",@"菌类":@"fungus",@"肉类":@"meat",@"保健品":@"health_food",
                 @"冷冻生鲜":@"freeze_food",@"干货":@"dry_good",@"特色饮品":@"beverage",@"包类":@"bag",
                 @"鞋服":@"clothes",@"首饰":@"jewelry",@"配件":@"parts",@"户外":@"outdoors",
                 @"生活":@"life",@"其他":@"other",@"食品":@"food",@"土特产":@"local_specialty",
                 @"百货":@"general_merchandise",@"针织品":@"hosiery",@"日常洗化":@"washing",@"季节商品":@"seasonal_merchandise",
                 @"烟酒茶":@"c_w_t",@"奶饮":@"milk_tea",@"方便食品":@"fast_food",@"休闲食品":@"leisure_food",
                 @"进口食品":@"import_food",@"米面调味":@"r_n_c",@"冷冻冷藏":@"freeze",@"纸制品":@"paper_product",
                 @"厨具用品":@"kitchen_ware",@"家电":@"household_appliances",@"家居用品":@"household_articles",@"文化用品":@"stationery_commodity",
                 @"毛巾":@"towel",@"内衣内裤":@"underwear_briefs",@"袜子":@"sock",@"床上用品":@"bedding_article",
                 @"个人护理":@"personal_care",@"家居清洁":@"household_clean",@"护肤品":@"skincare",@"美发护发":@"hairdressing",
                 @"口腔护理":@"mouth_care",
                 @"水果":@"fruit",@"蔬菜":@"vegetable",@"甜品":@"sweetmeat",
                 @"饮品":@"drink",@"简餐":@"simple_meal",@"鲜花":@"flower",
                 @"道具":@"prop",@"果蔬生鲜":@"fruit_vegetable",@"速食":@"fastfood",
                 @"派对":@"party"};
    _tanslateDic = @{@"民贸超市": @"Minmao company",@"糕点": @"Pastry",@"凉卤": @"Cold brine",
                     @"其他":  @"Others",@"食品":  @"Food",@"土特产": @"Local specialty",
                     @"百货": @"Department store",@"针织品": @"Knitwear",@"日常洗化": @"Cleaning products",
                     @"季节商品": @"Seasonal merchandise",@"烟酒茶": @"Tobacco and tea",
                     @"奶饮": @"Drink milk",@"休闲食品": @"Snacks",@"方便食品": @"instant food",
                     @"进口食品": @"Imported food",@"米面调味": @"Rice seasoning",@"冷冻冷藏": @"Cold storage",
                     @"纸制品": @"Paper Products",@"厨具用品": @"Kitchen utensils",@"家电": @"Household electrical",
                     @"家居用品": @"Home Furnishing",@"文化用品": @"Cultural products",@"毛巾": @"Towel",
                     @"内衣内裤": @"Underwear",@"袜子": @"Socks",@"床上用品": @"Bedding article",
                     @"家居清洁": @"Home cleaning",@"护肤品": @"Skin care",@"美发护发": @"Hair care",
                     @"口腔护理": @"Oral nursing",@"药材": @"Herbs",@"食品": @"Food",
                     @"服饰": @"Clothes",@"手工艺":  @"Handicraft",@"菌类": @"Fungus",
                     @"肉类":  @"Meats",@"保健品": @"Health products",@"冷冻生鲜":  @"Frozen fresh",
                     @"干货": @"Goods",@"特色饮品": @"Special drink",@"包类": @"Bags",
                     @"鞋服": @"Shoes & Clothing",@"首饰":  @"Jewelry",@"户外": @"Outdoors",
                     @"生活": @"Living",@"图书": @"Books",@"生鲜": @"Fresh",
                     @"奢侈礼品" : @"luxury",@"非物质文化遗产" : @"intangible_cultural",@"配件" : @"parts",
                     @"水果":@"fruit",@"蔬菜":@"vegetable",@"甜品":@"sweetmeat",
                     @"饮品":@"drink",@"简餐":@"simple_meal",@"鲜花":@"flower",
                     @"道具":@"prop",@"果蔬生鲜":@"fruit_vegetable",@"速食":@"fastfood",
                     @"派对":@"party"};
    
    // 默认值
    _sortBy = @"SALE";
    _sortType = @"DESC";
    
    // 返回顶部按钮
    _topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _topButton.frame = CGRectMake(kScreen_Width - 45.0, kScreen_Height, 40.0, 40.0);
    [_topButton setImage:[UIImage imageNamed:@"toTop"] forState:UIControlStateNormal];
    [_topButton addTarget:self action:@selector(scrollViewTop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_topButton];
    
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        self.topNumLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topPriceLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topScoreLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
    }
    
    [self setHeaderPopView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavgationBarBlackLine];
    
    _typeHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BDGanziTypeHeader" owner:nil options:nil].firstObject;
    _typeHeaderView.frame = CGRectMake(0.0, 0.0, kScreen_Width, 64.0);
    _typeHeaderView.tag = 943;
    [self.navigationController.view addSubview:_typeHeaderView];
    _typeHeaderView.searchTextField.delegate = self;// 否则再次进入不响应代理方法
    _typeHeaderView.searchTextField.layer.cornerRadius = 5.0;
    _typeHeaderView.searchTextField.layer.masksToBounds = YES;
    _typeHeaderView.delegate = self;
    
    if (self.secondTitle.length > 0 && self.thridTitle.length > 0) {
        if ([self.secondTitle isEqualToString:self.thridTitle]) {
            _typeHeaderView.searchTextField.text = NSLocalizedString(_tanslateDic[self.secondTitle], nil);
        } else {
            _typeHeaderView.searchTextField.text = NSLocalizedString(_tanslateDic[self.thridTitle], nil);
        }
    }
    
    if (_lastSearchContent.length > 0) {
        _typeHeaderView.searchTextField.text = _lastSearchContent;
    }
    
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        _typeHeaderView.searchTextField.placeholder = _typeHeaderView.searchTextField.text;
        _typeHeaderView.searchTextField.text = @"";
        [_typeHeaderView.searchTextField setValue:[UIFont fontWithName:@"Bzdbt" size:11.0] forKeyPath:@"_placeholderLabel.font"];
        [_typeHeaderView.searchTextField setValue:RGBColor(155, 134, 134) forKeyPath:@"_placeholderLabel.textColor"];
    }
    
    _typeHeaderView.searchImageView.hidden = YES;
    _typeHeaderView.searchLabel.hidden = YES;
    _typeHeaderView.searchTextField.placeholder = NSLocalizedString(@"Search: category brand products", nil);
    
    if (!_searchType) {
        [self reloadData:nil];
    } else if (_lastSearchContent.length == 0) {
        [_typeHeaderView.searchTextField becomeFirstResponder];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    navBarHairlineImageView.hidden = NO;
    
    if ([_typeHeaderView.searchTextField isFirstResponder]) {
        [_typeHeaderView.searchTextField resignFirstResponder];
    }
    if (_typeHeaderView) {
        [_typeHeaderView removeFromSuperview];
    }
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender {
    if (_typeHeaderView.searchTextField.isFirstResponder) {
        [_typeHeaderView.searchTextField resignFirstResponder];
    }
    NSString *url;
    NSString *sign = [self.storeType isEqualToString:@"HOLY_GARZE"] ? @"label" : @"storeType";
    if (_searchType) {// 搜索模式
        NSString *searchStr = _typeHeaderView.searchTextField.text;
        if (searchStr.length > 0) {
            _curPage = sender == self ? 1 : _curPage + 1;
            if (_curPage == 1) {// 消除没有更多数据的状态
                [_tableView.mj_footer resetNoMoreData];
            }
            url = [NSString stringWithFormat:@"%@%@?name=%@&currentPage=%ld&pageSize=%d&sortBy=%@&sortType=%@&%@=%@",
                   [BDNetworking shareInstance].baseUrl,
                   Good_Query,
                   searchStr,
                   (long)_curPage,
                   kPageSize,
                   _sortBy,
                   _sortType,
                   sign,
                   self.storeType];
        } else {
            [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"please input commodity name", nil)];
            return;
        }
    } else {
        _curPage = sender == self ? 1 : _curPage + 1;
        if (_curPage == 1) {// 消除没有更多数据的状态
            [_tableView.mj_footer resetNoMoreData];
        }
        if (_firstTitle.length > 0) {// 是否有1级分类
            url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&firstLevel=%@",
                   [BDNetworking shareInstance].baseUrl,
                   Good_Query,
                   (long)_curPage,
                   kPageSize,
                   levelDic[_firstTitle]];
        } else {
            url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d",
                   [BDNetworking shareInstance].baseUrl,
                   Good_Query,
                   (long)_curPage,
                   kPageSize];
        }
        
        if ([_firstTitle isEqualToString:@"奢侈礼品"]) {// update by wyp 2016-07-28
            if ([_secondTitle isEqualToString:@"其他"]) {
                url = [NSString stringWithFormat:@"%@&secondLevel=%@&sortBy=%@&sortType=%@&%@=%@",
                       url,
                       levelDic[_secondTitle],
                       _sortBy,
                       _sortType,
                       sign,
                       self.storeType];
            } else {
                url = [NSString stringWithFormat:@"%@&sortBy=%@&sortType=%@&%@=%@",
                       url,
                       _sortBy,
                       _sortType,
                       sign,
                       self.storeType];
            }
        } else {
            if (![_secondTitle isEqualToString:_thridTitle]) {
                url = [NSString stringWithFormat:@"%@&secondLevel=%@&thirdLevel=%@&sortBy=%@&sortType=%@&%@=%@",
                       url,
                       levelDic[_secondTitle],
                       levelDic[_thridTitle],
                       _sortBy,
                       _sortType,
                       sign,
                       self.storeType];
            } else {// 如果3级分类等于2级分类，就只取2级分类
                url = [NSString stringWithFormat:@"%@&secondLevel=%@&sortBy=%@&sortType=%@&%@=%@",
                       url,
                       levelDic[_secondTitle],
                       _sortBy,
                       _sortType,
                       sign,
                       self.storeType];
            }
        }
        if ([self.otherTitle isEqualToString:@"其他"]) {// 从分类过来点击的是其他/其他则要排除珠宝这一选项
            url = [NSString stringWithFormat:@"%@&excludeFirstLevels=%@",
                   url,
                   @"luxury"];
        }
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
    
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)url, NULL, NULL,  kCFStringEncodingUTF8 ));
    [[BDNetworking shareInstance] postWithUrl:encodedString sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_footer isRefreshing]) {
                [_tableView.mj_footer endRefreshing];
            }
        });
        if (error != nil) {
            hud.labelText = NSLocalizedString(@"Search Fail", nil);
            [hud hideAfterDelay:0.5];
            NSLog(@"搜索失败:%@",error);
        } else {
            [hud hideAfterDelay:0.5];
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                NSString *totalPage = resultDic[@"totalPage"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    if (sender == self) {
                        [_searchList removeAllObjects];
                    }
                    [_searchList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1 && _curPage >= [totalPage integerValue]) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    } else { // 刷新之前的数据应该清零
                        [_searchList removeAllObjects];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }
        }
    }];
}

- (void)setHeaderPopView {
    NSArray *tmpArray = @[NSLocalizedString(@"home", nil),NSLocalizedString(@"message", nil)];
    NSArray *images = @[@"homeback",@"messageback"];
    //左
    _popView = [[SimplePopupView alloc] initWithFrame:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)
                                         andDirection:PopViewDirectionTop
                                            andTitles:tmpArray
                                            andImages:images
                                       trianglePecent:0.5]; //箭头位于popview中间0.5位置
    [self.navigationController.navigationBar showPopView:_popView AtPoint:CGPointMake(0.5, 0)];//箭头位于button的x=0.y=0.5比例处
    _popView.delegate = self; //需要正式使用时注意代理
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        navBarHairlineImageView = imageView2;
                        navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)scrollViewTop:(UIButton *)sender {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.3 animations:^{
            UIView *view = [self.navigationController.view viewWithTag:956];
            view.y = 0.0;
            self.topContainerview.y = 64.0;
        } completion:^(BOOL finished) {
            self.navigationController.navigationBar.hidden = NO;
            //            self.topContainerviewConstraint.constant = 64.0;
            willBeginScroll = NO;
        }];
    });
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.searchType = YES;
    textField.text = @"";
    // 是否循序文本字段开始编辑
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self reloadData:self];
    return YES;
}

#pragma mark BDGanziTypeHeaderView delegate

- (void)backMethod {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)homeMethod:(UIButton *)sender {
    [_popView show];
}

- (void)simplePopupView:(SimplePopupView *)popView clickAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"代理方法，点击了第%ld行",(long)indexPath.row);
    if (indexPath.row == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } else if (indexPath.row == 1) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    }
}

#pragma mark tableView dataSrouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchList.count > 0 ? _searchList.count : 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_searchList.count > 0) {
        static NSString *cellStr = @"searchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        // 商品图片
        NSString *goodImageUrl = _searchList[indexPath.row][@"icon"];
        UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
        if (![goodImageUrl isEqual:[NSNull null]]) {
            [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (image.size.width / image.size.height >= 1.1) {// banner商品(宽:高) 1.8:1 显示
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {
                        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                            constraint.constant = 95.0 / (image.size.width / image.size.height);
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            constraint.constant = 8;
                        }
                    }
                } else if (image.size.width / image.size.height <= 0.9) {
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {
                        if (constraint.firstAttribute == NSLayoutAttributeWidth) {
                            constraint.constant = 92.0 * (image.size.width / image.size.height);
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            CGFloat minus =  92.0 - 92.0 * (image.size.width / image.size.height);
                            constraint.constant = 8 + minus / 2;
                        }
                    }
                } else {
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {// NSLayoutAttributeLeading
                        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                            constraint.constant = 95.0;
                        }
                        if (constraint.firstAttribute == NSLayoutAttributeWidth) {
                            constraint.constant = 92.0;
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            constraint.constant = 8;
                        }
                    }
                }
            }];
        }
        // 商品名称
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *goodName = _searchList[indexPath.row][@"name"];
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        // 商品描述
        UILabel *goodDescLabel = (UILabel *)[cell viewWithTag:103];
        NSString *goodDesc = _searchList[indexPath.row][@"address"];
        if (![goodDesc isEqual:[NSNull null]]) {
            goodDescLabel.text = [NSString stringWithFormat:@"产地：%@",goodDesc];
        }
        // 商品销量
        UILabel *goodNumLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodNum = _searchList[indexPath.row][@"saleNum"];
        if (![goodNum isEqual:[NSNull null]]) {
            goodNumLabel.text = [NSString stringWithFormat:@"销量：%@",goodNum];
        }
        // 商品折扣价格
        UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:106];
        // 商品价格
        UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:107];
        
        NSString *goodDiscount = _searchList[indexPath.row][@"commodityPrice"][@"discount"];
        NSString *goodPrice = _searchList[indexPath.row][@"commodityPrice"][@"price"];
        if (![goodDiscount isEqual:[NSNull null]] &&
            ![goodPrice isEqual:[NSNull null]]) {
            // 折扣价格
            CGFloat discount = [goodDiscount floatValue];
            CGFloat price = [goodPrice floatValue];
            goodDiscountLabel.text = [NSString stringWithFormat:@"¥ %.2f",price * discount];
            // 价格
            NSString *str = [NSString stringWithFormat:@"¥ %.2f",[goodPrice floatValue]];
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attribtDic];
            goodPriceLabel.attributedText = attribtStr;
            if (discount >= 1.0 || [goodPriceLabel.text isEqualToString:goodDiscountLabel.text]) {
                goodPriceLabel.hidden = YES;
            } else {
                goodPriceLabel.hidden = NO;
            }
        }
        
        return cell;
    } else {
        static NSString *cellStr = @"noCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        return cell;
    }
    
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    _tableView.scrollEnabled = _searchList.count > 0 ? YES : NO;
    return _searchList.count > 0 ? 108.0 : kScreen_Height - 104.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchList.count > 0) {
        NSString *commodityId = _searchList[indexPath.row][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
            
            _lastSearchContent = _typeHeaderView.searchTextField.text;
        }
    }
}

#pragma mark - UIScrollView delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        beginOffsetY = offsetY;
        willBeginScroll = YES;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        
        if (offsetY > 100 && !showTop) {
            showTop = YES;
            [UIView animateWithDuration:0.3 animations:^{
                _topButton.y = kScreen_Height - 47.0 - 20.0;
            } completion:^(BOOL finished) {
                
            }];
        }
        if (offsetY < 100 && showTop){
            showTop = NO;
            [UIView animateWithDuration:0.3 animations:^{
                _topButton.y = kScreen_Height;
            } completion:^(BOOL finished) {
            }];
        }
    }
}

#pragma mark - IBActions

- (IBAction)classButtonPressed:(UIButton *)sender {
    NSInteger index = sender.tag - 400;
    NSInteger count = 0;
    UIView *superView = sender.superview;
    UIView *containerView = superView.superview;
    
    for (UIView *view in containerView.subviews) {
        count++;
        if (count == index) {
            UILabel *label = [view viewWithTag:100 + index];
            label.textColor = RGBColor(215, 19, 33);
            UIImageView *imageView = [view viewWithTag:200 + index];
            imageView.hidden = NO;
            UIView *line = [view viewWithTag:300 + index];
            line.hidden = NO;
        } else {
            UILabel *label = [view viewWithTag:100 + count];
            label.textColor = RGBColor(102, 102, 102);
            UIImageView *imageView = [view viewWithTag:200 + count];
            imageView.hidden = YES;
            UIView *line = [view viewWithTag:300 + count];
            line.hidden = YES;
        }
    }
    sender.selected = !sender.selected;
    UIImageView *imageView = [superView viewWithTag:200 + index];
    if (sender.selected) {
        imageView.image = [UIImage imageNamed:@"search_antiTrangle"];
        _sortType = @"DESC";
    } else {
        imageView.image = [UIImage imageNamed:@"search_trangle"];
        _sortType = @"ASC";
    }
    
    if (sender.tag == 401) {// 销量
        _sortBy = @"SALE";
    } else if (sender.tag == 402) {//价格
        _sortBy = @"PRICE";
    } else if (sender.tag == 403) {// 评分
        _sortBy = @"GRADE";
    }
    [self reloadData:self];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
